import {ref, reactive, onMounted} from 'vue'
import {message} from "ant-design-vue";
import {VXETable} from 'vxe-table'
import {ContactService} from "@/views/erp/system/contact/contactService";
import mtUtil from "@/utils/mtUtil";
import validate from "ele-admin-pro/packages/validate";

export default function ContactMapMannage(props) {

  let id = 0;
  //vxeTable的映射对象
  const contactTable = ref({})

  const isDetail = ref(props.isDetail)
  //管理列表展示
  let contactList = ref([]);

  let jobTitleList = mtUtil.getDict("往来单位联系人职务")

  let business = reactive({businessId: props.businessId, entityName: props.entity})

  let contactsTemp = ref(props.contacts)
  //表格配置
  const tableConfig = {
    border: true,
    showHeaderOverflow: true,
    showOverflow: true,
    resizeable: true,
    keepSource: true,
    highlightHoverRow: true,
    align: "center",
    columns: [
      {
        field: 'name',
        title: '姓名',
        minWidth: "10%",
        fixed: "left",
        editRender: {name: 'input', attrs: {type: 'text'}},
      },
      {
        field: 'telephone',
        title: '手机号',
        minWidth: "15%",
        fixed: "left",
        editRender: {name: 'input', attrs: {type: 'text'}},
      },
      {
        field: 'email',
        title: '电子邮箱',
        minWidth: "15%",
        editRender: {name: 'input', attrs: {type: 'text'}},
      },
      {
        field: 'landLine',
        title: '座机',
        minWidth: "12%",
        editRender: {name: 'input', attrs: {type: 'text'}},
      },
      {
        field: 'wechat',
        title: '微信号',
        minWidth: "12%",
        editRender: {name: 'input', attrs: {type: 'text'}},
      },
      {
        field: 'jobTitle',
        title: '职务',
        minWidth: "10%",
        editRender: {name: '$select', options: jobTitleList, props: {clearable: true}}
      },
      {
        field: 'addressName',
        title: '地址',
        minWidth: "20%",
      },
      {
        title: "状态",
        minWidth: "10%",
        slots: {default: 'status'},
        fixed: 'right'
      },
    ],

    mouseConfig: {
      selected: true
    },
    checkboxConfig: {range: true},


    //todo :页面数据提示配置
    tooltipConfig: {
      showAll: true,
      enterable: true,
    },


    /*TODO:工具栏配置*/
    toolbarConfig: {
      showAll: true,
      enterable: true,
      className: 'vxe-toolbar-mt',
      slots: {buttons: 'component_title', tools: 'tool_button'},
      refresh: false,
      import: false,
      export: false,
      print: false,
      zoom: true,
      custom: false
    },

    //键盘导航设置
    keyBoardConfig: {
      isArrow: true,
      isDel: true,
      isEnter: true,
      isTab: true,
      isEdit: true,
      editMethod({row, column}) {
        const $table = contactTable.value
        // 重写默认的覆盖式，改为追加式
        if (row.status !== "停用" && !isDetail.value) {
          $table.setActiveCell(row, column)
        }
      }
    },

    //表格编辑设置
    editConfig: {
      trigger: 'dblclick',
      mode: 'cell',
      showStatus: true,
      icon: "fa",
      activeMethod({row}) {
        return row.status !== "停用" && !isDetail.value;
      }
    },


    editRules: {
      name: [
        {required: true, message: '联系人姓名必须输入',trigger: "onSubmit"},
      ],

      telephone: [
        {required: true, message: "联系人手机号必须输入",trigger: "onSubmit"},
        {
          pattern: validate.phoneStrong,
          message: "请输入正确的电话",trigger: "onSubmit"
        }, {
          validator({cellValue}) {
            if (contactMap[cellValue]) {
              return new Error("同一个业务存在相同手机号")
            } else {
              contactMap[cellValue] = cellValue
            }
          },trigger: "onSubmit"
        }
      ],
      landline: [
        {
          pattern: validate.tel,
          message: "请输入正确的座机号码",
          trigger: "onSubmit",
        }
      ],
      email: [
        {
          pattern: validate.email,
          message: "请输入正确的邮箱",
          trigger: "onSubmit",
        }
      ],
      wechat: [
        {
          //微信官方定义的微信号规则
          // 1、可使用6-20个字母、数字、下划线和减号；
          // 2、必须以字母开头（字母不区分大小写）；
          // 3、不支持设置中文。
          pattern: /^[a-zA-Z][a-zA-Z0-9_-]{5,19}$/,
          message: "请输入正确的微信号",
          trigger: "onSubmit",
        }
      ],
      jobTitle: [],
      address: [],
    }
  }

  let AddressEntity=reactive({
    addressAbbreviation: "",
    addressType: "",
    businessID: "",
    detailedAddress: "",
    province: "",
    city: "",
    district: "",
    streetAddress: "",
    addressLongitude: 0,
    addressLatitude: 0,
    zipCode: "",
  })

  //为只读状态下隐藏操作按钮
  if (!isDetail.value) {
    tableConfig.columns.push({
      title: '操作',
      minWidth: "12%",
      slots: {default: 'operate'},
      fixed: 'right'
    })
  }

  const changeHeight = (tableHeight) => {
    if (tableHeight) {
      tableConfig.height = tableHeight;
    }
  }
  changeHeight(props.height);


  //渲染表格
  onMounted(() => {
    if (contactsTemp.value) {
      contactChange(contactsTemp.value)

    } else {
      reload(business);

    }
  })

  const getAddress=(address,row)=>{
    console.log("row",row)
    let addressTemp=reactive(address);
    row.addressName=addressTemp.name;
    row.address=addressTemp
  }
  //页面的重载
  let reload = (business) => {
    console.log(business)
    const conditions = {
      entityName: business.entityName,
      businessId: business.businessId,
      status: "启用$|$停用"
    }

    const queryParams = {}
    //获取筛选结果（无懒加载）
    queryParams.filters = conditions

    //该方法所有语句结束后执行
    ContactService.findContacts(queryParams).then((res) => {
      console.log("findContacts ", res)
      contactChange(res.data.datas)

      //vxetable的data改变，但未渲染到对应的表格中
      // contactList.value.push({})
      // contactChange(contactList.value)
    }).catch((error) => {
      message.error(error.message);
    })

  }

  //合并新数组到旧数组，新数组全部保留，旧数组只保留新增的部分,即eid为空的对象
  let contactChange = (contacts) => {
    //将空地址处理
    for (let i = 0; i < contacts.length; i++) {
      contacts[i].id = id++;

      if (contacts[i].address === null) {
        contacts[i].address = {
          addressAbbreviation: "",
          addressType: "",
          businessID: null,
          detailedAddress: "",
          province: "",
          city: "",
          district: "",
          streetAddress: "",
          addressLongitude: 0,
          addressLatitude: 0,
          zipCode: "",
        }
      }
    }
    let list = contacts;
    console.log("当前数组为", contactList.value)

    //合并原数组中的新增对象
    for (let i = 0; i < contactList.value.length; i++) {

      let item = contactList.value[i]
      // console.log("item", item)
      if ((item.eid === undefined || item.eid === null) && item.telephone !== undefined) {
        if (item.address === null) {
          item.address = {
            addressAbbreviation: "",
            addressType: "",
            businessID: null,
            detailedAddress: "",
            province: "",
            city: "",
            district: "",
            streetAddress: "",
            addressLongitude: null,
            addressLatitude: null,
            zipCode: "",
          }
        }
        item.id = id++
        list.push(item);
      }
    }

    contactList.value = list;

    console.log("contactList", contactList);
    // const $table = contactTable.value
    // console.log("table", $table)
  }

  //新增
  const insertEvent = async (row) => {

    let contactEntityData = reactive({
      id: id++,
      "name": "",
      "entityName": business.entityName,
      "businessId": business.businessId,
      "telephone": "",
      "landline": "",
      "email": "",
      "wechat": "",
      "jobTitle": "",
      "addressId": null,
      "address": null,
      "addressName": "",
    })

    contactEntityData.address = {
      addressAbbreviation: "",
      addressType: "",
      businessID: "",
      detailedAddress: "",
      province: "",
      city: "",
      district: "",
      streetAddress: "",
      addressLongitude: 0,
      addressLatitude: 0,
      zipCode: "",
    }

    const $table = contactTable.value
    const {row: newRow} = await $table.insertAt(contactEntityData,row)
    await $table.setActiveCell(newRow, 'name')

    //新增数据无法动态添加进代理对象，
    // 需要之后获取对象时通过$table.getInsertRecords()获取所有新增后的对象
    console.log(newRow)
    console.log(contactList)
    // console.log($table.data)
    // console.log($table.getInsertRecords())
  }


  // //新增
  // const insertEvent = () => {
  //   let contactEntityData = reactive({
  //     id: id++,
  //     "name": "",
  //     "entityName": business.entityName,
  //     "businessId": business.businessId,
  //     "telephone": "",
  //     "landline": "",
  //     "email": "",
  //     "wechat": "",
  //     "jobTitle": "",
  //     "addressId": null,
  //     "address": null,
  //     "addressName": "",
  //   })
  //
  //   contactEntityData.address = {
  //     addressAbbreviation: "",
  //     addressType: "",
  //     businessID: "",
  //     detailedAddress: "",
  //     province: "",
  //     city: "",
  //     district: "",
  //     streetAddress: "",
  //     addressLongitude: 0,
  //     addressLatitude: 0,
  //     zipCode: "",
  //   }
  //
  //   const $table = contactTable.value
  //   // const {row: newRow} = await $table.insertAt(contactEntityData, row)
  //   // await $table.setActiveCell(newRow, 'name')
  //
  //   let list=contactList.value;
  //   list.unshift(contactEntityData);
  //   contactList.value=list;
  //   //新增数据无法动态添加进代理对象，
  //   // 需要之后获取对象时通过$table.getInsertRecords()获取所有新增后的对象
  //   // console.log(newRow)
  //   console.log(contactList)
  //   $table.loadData(contactList.value)
  //   // console.log($table.data)
  //   // console.log($table.getInsertRecords())
  // }
  //移除数据


  const removeEvent = (row) => {
    if (row.eid) {
      ContactService.deleteContact(row.eid).then((res) => {
        console.log("删除的对象为", res);
      }).catch((error) => {
        message.error(error.message);
      })
    }
    let list = contactList.value;
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === row.id) {
        list.splice(i, 1);
        break;
      }
    }
    contactList.value = list;
    const $table = contactTable.value
    // console.log($table)
    $table.remove(row)


    console.log("删除后的数组", contactList.value)


  }

  //修改状态
  const changeStatus = (row) => {
    if (row.status === "启用") {
      row.status = "停用"
    } else {
      row.status = "启用"
    }
  }

  var contactMap = reactive({});
  const validContacts = async () => {
    const $table = contactTable.value
    contactMap = reactive({});
    const errMap = await $table.validate(true).catch(errMap => errMap)
    console.log("errMap", errMap)
    if (errMap) {

      VXETable.modal.message({status: 'error', content: '联系人校验不通过！'})

      return false
    } else {
      // VXETable.modal.message({status: 'success', content: '联系人校验成功！'})

      return true
    }
  }
  //获取当前列表中的数据，结果为null说明验证失败
  //Todo :表单验证
  const getContactList =async () => {
    const $table = contactTable.value
    contactMap = reactive({});
    const errMap = await $table.validate(true).catch(errMap => errMap)
    console.log("contactsErrMap", errMap)
    if (errMap) {

      // VXETable.modal.message({status: 'error', content: '联系人校验不通过！'})

      return null
    } else {
      // VXETable.modal.message({status: 'success', content: '联系人校验成功！'})
      let list = contactTable.value.getInsertRecords();
      contactList.value.forEach((contact) => {
        list.push(contact)
      })

      console.log("contactList", list);

      return list
    }
    // let list = contactTable.value.getInsertRecords();
    // contactList.value.forEach((contact) => {
    //   list.push(contact)
    // })
    //
    // console.log("contactList", list);
    //
    // return list
  }


  return {
    AddressEntity,
    getAddress,
    tableConfig,
    jobTitleList,
    changeStatus,
    contactList,
    contactTable,
    reload,
    contactChange,
    insertEvent,
    removeEvent,
    getContactList,
    validContacts,
  }

}
